<template>
  <div>
    <ex-dialog width="1000px" class="ex-diolog" :title="title" :visible="visible" @closeDialog="handleClose">
      <el-form ref="form" :model="ruleForm" :rules="rules" label-width="120px"
        :disabled="pathType == 'detail' || pathType == 'edit' ? true : false">
        <el-form-item label="店铺名称：" prop="merchantId" :key="1">
          <el-select :disabled="pathType == 'edit' ? true : false" filterable v-model="ruleForm.merchantId"
            placeholder="请选择" clearable size="small" @change="changeMerchantId">
            <el-option v-for="item in merchantList" :key="item.id" :label="item.value" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="发行方：" prop="" :key="2">
          <el-input v-model="issuerName" placeholder="请输入发行方" :disabled="true" />
        </el-form-item>
        <div class="max_title">赚卡信息</div>
        <el-form-item label="卡名称：" prop="name" :key="3">
          <el-input v-model="ruleForm.name" placeholder="请输入卡名称" />
        </el-form-item>
        <el-form-item label="售价：" prop="price" :key="4">
          <el-input v-model="ruleForm.price" placeholder="请输入售价" />
        </el-form-item>
        <el-form-item label="发行数量：" prop="issueTotal" :key="5">
          <el-input v-model="ruleForm.issueTotal" placeholder="请输入发行数量" />
        </el-form-item>
        <el-form-item label="卡面:" prop="cover" :key="6">
          <ImageUploadMore :limit="1" :fileSize="20" @successImg="getCover" :value="ruleForm.cover">
          </ImageUploadMore>
        </el-form-item>
        <el-form-item label="卡介绍:" prop="imgList" :key="7">
          <ImageUploadMore :limit="6" :fileSize="20" @successImg="getImgList" :value="ruleForm.imgList">
          </ImageUploadMore>
        </el-form-item>
        <el-form-item label="限购：" prop="" :key="8">
          <el-switch active-text="开启" inactive-text="关闭" v-model="ruleForm.limitBuyType" :active-value="'2'"
            :inactive-value="'1'"></el-switch>
        </el-form-item>
        <el-form-item label="" prop="limitAmount" v-if="ruleForm.limitBuyType == 2" :key="9">
          <el-input v-model="ruleForm.limitAmount" placeholder="请输入" ref="limitAmountRef">
            <template slot="append">份</template>
          </el-input>
        </el-form-item>
        <div class="max_title">权益卡信息</div>
        <el-form-item label="权益名称：" prop="equityName" :key="10">
          <el-input type="text" v-model="ruleForm.equityName" placeholder="请输入权益名称" />
        </el-form-item>
        <el-form-item label="权益价值：" prop="equityWorth" :key="11">
          <el-input type="text" v-model="ruleForm.equityWorth" placeholder="请输入权益价值" />
        </el-form-item>
        <el-form-item label="使用说明：" prop="useExplain" :key="12">
          <el-input type="textarea" :autosize="{ minRows: 5, maxRows: 10 }" placeholder="请输入内容"
            v-model="ruleForm.useExplain">
          </el-input>
        </el-form-item>
        <template v-if="isChain">
          <div class="max_title">权益可用店铺</div>
          <el-form-item label="选择店铺：" prop="merchantIdList" :key="13">
            <el-select filterable v-model="ruleForm.merchantIdList" placeholder="请选择" clearable multiple size="small">
              <el-option v-for="item in chainList" :key="item.id" :label="item.value" :value="item.id" />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="pathType == 'add'">
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确认申请</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-if="pathType == 'edit'">
        <el-button type="primary" @click="agreedForm" :loading="submitLoading">同意发行</el-button>
        <el-button @click="handleRefused">拒绝发行</el-button>
      </div>
    </ex-dialog>
    <refusedDialog :id='id' v-if="refusedDialog" :pathType="pathType" :visible.sync="refusedDialog"
      @success="_handleSuccess" />
  </div>
</template>
<script>
// api
// import {
//   getDetail,
//   approved,
//   reject
// } from '@/api/regitserVerify'

import {
  addApply,
  applyDetail,
  shopSelect,
  chainSelect,
  refusedMerchant
} from "@/api/merchantsNFR/castingApplication";
import refusedDialog from "./refusedDialog";
export default {
  props: {
    visible: Boolean,
    id: String,
    pathType: String,
  },
  components: {
    refusedDialog
  },
  data() {
    var validateIssueTotal = (rule, value, callback) => {
      var reg = /^[1-9]\d*|0$/
      if (value === '') {
        callback(new Error('请填写发行数量'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入大于等于0的整数'));
      } else {
        callback()
      }
    };
    var validatePrice = (rule, value, callback) => {
      var reg = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
      if (value === '') {
        callback(new Error('请填写售价'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入大于0的数值，可保留两位小数'));
      } else {
        callback()
      }
    };
    var validateEquityWorth = (rule, value, callback) => {
      var reg = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
      if (value === '') {
        callback(new Error('请输入权益价值'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入大于0的数值，可保留两位小数'));
      } else {
        callback()
      }
    };
    var validLimitAmount = (rule, value, callback) => {
      var reg = /(^[1-9]\d*$)/
      if (value === '') {
        callback(new Error('请填写限购数量'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入大于0的正整数'));
      } else {
        callback()
      }
    };
    return {
      refusedDialog: false,
      title: '新增申请',
      submitLoading: false,
      cardOptin: [],
      merchantList: [],
      chainList: [],
      isChain: false,
      chainId: '',
      issuerName: '',
      defaultMerchantId: '',//默认商家
      ruleForm: {
        merchantId: '', //商家id
        chainId: '', //连锁总部id
        name: '', //卡名称
        price: '', //售价
        issueTotal: '', //发行数量
        cover: '', //卡面
        imgList: '', //卡介绍
        equityName: '', //权益名称
        equityWorth: '', //权益价值
        useExplain: '', //	使用说明
        merchantIdList: [], //核销店铺id数组
        limitBuyType: '',//限购类型 1 不限购 2 限购
        limitAmount: '',//限购数量
      },
      rules: {
        // type: [{
        //   required: true,
        //   message: '请选择',
        //   trigger: 'change'
        // }, ],
        name: [{
          required: true,
          message: '请填写卡名称',
          trigger: ['blur','change']
        },
        ],
        price: [{
          required: true,
          validator: validatePrice,
          trigger: ['blur','change']
        },
        ],
        issueTotal: [{
          required: true,
          validator: validateIssueTotal,
          trigger: ['blur','change']
        },
        ],
        cover: [{
          required: true,
          message: '请上传图片',
          trigger: ['change', 'blur']
        },
        ],
        imgList: [{
          required: true,
          message: '请上传图片',
          trigger: ['change', 'blur']
        },
        ],
        equityName: [{
          required: true,
          message: '请输入权益名称',
          trigger: ['blur','change']
        },],
        equityWorth: [{
          required: true,
          validator: validateEquityWorth,
          trigger: ['blur','change']
        },],
        useExplain: [{
          required: true,
          message: '请输入内容',
          trigger: ['blur','change']
        },],
        limitAmount: [{
          required: true,
          validator: validLimitAmount,
          trigger: ['blur','change']
        },],
      }
    }
  },
  watch: {
    'ruleForm.merchantIdList': {
      handler(newV, oldV) {
        console.log("watch", typeof newV)
        if (newV.length == 0 && this.isChain) {
          console.log('哈哈哈哈')
          this.ruleForm.merchantIdList = [this.chainList[0].id]
        }
      },
      deep: true
    }
  },
  created() {

    this.getShop()
  },
  mounted() {
    // this.getDetail()
    if (this.pathType == 'add') {
      this.title = '新增申请'
    } else if (this.pathType == 'edit') {
      this.title = '申请审核'
      this.getDetail()

    } else if (this.pathType == 'detail') {
      this.title = '申请审核'
      this.getDetail()

    }
  },
  methods: {
    getDetail() {
      applyDetail(this.id).then(res => {
        console.log('获取详情', res)
        const { result } = res
        this.ruleForm = result
        if (this.pathType == 'edit' || this.pathType == 'detail') {
          this.filterMerchant(result.merchantId)
        }

      })
    },

    //获取店铺下拉
    getShop() {
      shopSelect().then(res => {
        this.merchantList = res.result
      })
    },
    //获取连锁店铺
    getChain() {
      chainSelect(this.ruleForm.chainId).then(res => {
        this.chainList = res.result
        var arr = [...res.result]
        if (this.pathType == 'add') {
          this.ruleForm.merchantIdList[0] = arr.splice(0, 1)[0].id
        }
        // console.log('this.ruleForm.merchantIdList',this.ruleForm.merchantIdList)
      })
    },
    handleClose() {
      this.$emit('update:visible', false)
    },
    //选择店铺
    changeMerchantId(e) {
      console.log(e)
      this.ruleForm.merchantIdList = []
      this.ruleForm.chainId = ''
      this.filterMerchant(e)

    },
    filterMerchant(e) {
      this.merchantList.forEach(item => {
        if (item.id == e) {
          this.issuerName = item.additionalValue
          if (item.data == '') {
            this.isChain = false
          } else {

            this.ruleForm.chainId = item.data
            this.isChain = true
            this.getChain()
          }
        }
      })
    },
    //卡面
    getCover(e) {
      console.log('e', e)
      if (e != '') {
        this.ruleForm.cover = e
      }
    },
    getImgList(e) { //图片
      console.log('e', e)
      if (e != '') {
        this.ruleForm.imgList = e.split(",")
      } else {
        this.ruleForm.imgList = []
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.submitLoading = true
          var data = {
            ...this.ruleForm
          }
          // 打开遮罩层
          // this.$modal.loading("正在处理中数据，请稍后...");
          addApply(data).then(response => {
            this.$message.success('新增成功');
            this.handleClose()
            this.$emit('success')
            this.submitLoading = false
          }).catch(() => {
            this.submitLoading = false
          });
        }
      });
    },
    //拒绝申请
    handleRefused() {
      this.refusedDialog = true
    },
    //同一发行
    agreedForm() {
      var data = {
        id: this.id,
        status: 2,
      }
      refusedMerchant(data).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$emit('success')
          this.handleClose()
        }
      })
    },
    handleSuccess(msg) {
      if (msg === '已拒绝') {
        var type = 'error'
      } else {
        var type = 'success'
      }
      this.$message({
        message: msg,
        type: type,
        duration: 1500,
        onClose: () => {
          this.handleClose()
          this.$emit('success')
        }
      })
    },
    _handleSuccess() {
      this.handleClose()
      this.$emit('success')
    },


  }
}
</script>
<style lang="scss" scoped>
.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
  }

  .grid-layout {
    width: 560px;
    margin: 0 auto;
  }

  .img {
    display: block;
    width: 100px;
    height: auto;
  }
}

.max_title {
  font-size: 18px;
  color: #1890ff;
  font-weight: 600;
  height: 40px;
  line-height: 40px;
  border-bottom: 3px solid #1890ff;
  width: 750px;
  margin-bottom: 20px;
}

.el-input {
  width: 300px;
}

.el-select {
  width: 300px;
}

.el-textarea {
  width: 500px;
}
</style>
